import re

# 定义所有必需的标签（不带尖括号）
REQUIRED_TAG_NAMES = [
    "summary",
    "comparison",
    "evaluation",
    "synthesis",
    "rationale",
    "final_answer"
]

def validate_structured_output(output_str: str) -> (bool, list):
    """
    验证输出字符串是否包含所有必需的结构化标签对。

    这个函数会检查每个必需的标签是否都以 <tag>...</tag> 的形式成对出现。

    Args:
        output_str: 模型生成的完整输出字符串。

    Returns:
        A tuple containing:
        - bool: 如果所有标签都存在且格式正确，则为 True，否则为 False。
        - list: 缺失或格式不正确的标签名称列表。
    """
    if not output_str or not isinstance(output_str, str):
        return False, REQUIRED_TAG_NAMES

    missing_tags = []
    for tag_name in REQUIRED_TAG_NAMES:
        # 使用正则表达式查找 <tag>...</tag> 模式。
        # re.DOTALL 使得 '.' 可以匹配包括换行符在内的任意字符。
        pattern = f"<{tag_name}>.*?</{tag_name}>"
        if not re.search(pattern, output_str, re.DOTALL):
            missing_tags.append(tag_name)

    is_valid = len(missing_tags) == 0
    return is_valid, missing_tags

# --- 示例 ---

# 示例1：一个格式完全正确的输出
valid_output = """
<summary>Agent A suggests X, Agent B suggests Y.</summary>
<comparison>They both agree on Z, but differ on X vs Y.</comparison>
<evaluation>Agent A's logic is sound. Agent B's data is more recent.</evaluation>
<synthesis>By combining A's logic with B's data, we can achieve W.</synthesis>
<rationale>We choose W because it leverages the strengths of both agents.</rationale>
<final_answer>The final answer is W.</final_answer>
"""

# 示例2：一个缺少 <rationale> 和 <final_answer> 的输出
invalid_output = """
<summary>Agent A suggests X, Agent B suggests Y.</summary>
<comparison>They both agree on Z, but differ on X vs Y.</comparison>
<evaluation>Agent A's logic is sound. Agent B's data is more recent.</evaluation>
<synthesis>By combining A's logic with B's data, we can achieve W.</synthesis>
"""

# --- 测试代码 ---
is_valid_1, missing_1 = validate_structured_output(valid_output)
print(f"示例1是否有效: {is_valid_1}") # Expected: True
print(f"示例1缺失的标签: {missing_1}")   # Expected: []

print("-" * 20)

is_valid_2, missing_2 = validate_structured_output(invalid_output)
print(f"示例2是否有效: {is_valid_2}") # Expected: False
print(f"示例2缺失的标签: {missing_2}")   # Expected: ['rationale', 'final_answer']